import * as types from './actionTypes';
import {ToastAndroid} from 'react-native';

const fetchTag = () => {
  return (dispatch, getStore) => {
     dispatch({
        type: types.FetchTag
     });
      fetch('http://42.159.143.17:6080/alfresco/s/api/tags/workspace/SpacesStore',{
           method: 'GET',
           headers:{
             Authorization:'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE='
           }
          })
      .then(res => {
        return res.json();
      })
      .then(tags => {

        dispatch({
         	 type: types.FetchTagSuccess,
         	 tags
        });
      });
     };
 }
 const addTag = (tag)=>{
   return {
     type: types.AddTag,
     tag
   }
 }
 const fetchFileByTag = (tag)=>{
  return (dispatch, getStore) => {
   var promise = fetch('http://42.159.143.17:6080/alfresco/s/api/tags/workspace/SpacesStore/'+tag+'/nodes',{
        method: 'GET',
        headers:{
          Authorization:'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE='
        }
      });
    promise.then(res => {
        return res.json();
    })
    .then(nodes => {
        var promises = [];
        for(var i = 0; i < nodes.length; i++){
          let index = nodes[i].url.lastIndexOf('/');
          if(index != -1){
            let uuid = nodes[i].url.substring(index+1);
            promises.push(fetchFileInfoByUUID(uuid,i))
          }
        }
        Promise.all(promises).then((result)=>{
          let files = [];
          for(let i = 0;i < result.length;i++){
            if(result[i].results.items && result[i].results.items.length != 0){
              files.push(result[i].results.items[0]);
            }
          }
          dispatch({
            type:types.FetchFileByTag,
            files
          });
        });
      });
   };
};

const removeTag = (tag,callback) => {
  return (dispatch, getStore) => {
      removeTagApi(tag).then((res)=>{
        if(res.result == true){
          ToastAndroid.show("删除Tag成功",ToastAndroid.SHORT);
          dispatch({
            type:types.RemoveTag,
            tag
          })
           callback();
          // navigator.pop();
        }
      })
  }
}



  var removeTagApi = function(tag){
    return fetch('http://42.159.143.17:6080/alfresco/s/api/tags/'+tag,{
         method: 'DELETE',
         headers:{
           Authorization:'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE='
         }
       }).then((res)=>{
         return res.json();
       });
  }
  var fetchFileInfoByUUID = function(id,i){
    return fetch('http://42.159.143.17:6080/alfresco/s/dms/nodeDetailedInfo?uuid='+id,{
         method: 'GET',
         headers:{
           Authorization:'Basic dHcuZmVuZ0BoYWloYW5neXVuLmNvbToxMTExMTE='
         }
       }).then((res)=>{
         return res.json();
       });

  }


export default {
   fetchTag,
   addTag,
   fetchFileByTag,
   removeTag
}
